package com.zjj.day0425.object.copy;

/**
 * @author zhoujunjie
 * @desc TODO
 * @date 2025/4/25
 */
import java.util.ArrayList;
import java.util.List;

class Address implements Cloneable {
    private String city;

    public Address(String city) {
        this.city = city;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    @Override
    public String toString() {
        return "Address{city='" + city + "'}";
    }
}

class Student implements Cloneable {
    private String name;
    private Address address;
    private List<String> courses;

    public Student(String name, Address address, List<String> courses) {
        this.name = name;
        this.address = address;
        this.courses = courses;
    }

    public String getName() {
        return name;
    }

    public Address getAddress() {
        return address;
    }

    public List<String> getCourses() {
        return courses;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    public Student deepCopy() throws CloneNotSupportedException {
        // 复制基本类型属性
        Student clonedStudent = (Student) super.clone();
        // 深拷贝引用类型属性
        clonedStudent.address = (Address) this.address.clone();
        // 复制列表
        clonedStudent.courses = new ArrayList<>(this.courses);
        return clonedStudent;
    }

    @Override
    public String toString() {
        return "Student{name='" + name + "', address=" + address + ", courses=" + courses + "}";
    }
}

public class CopyWork {
    public static void main(String[] args) throws CloneNotSupportedException {
        Address originalAddress = new Address("安徽");
        List<String> originalCourses = new ArrayList<>();
        originalCourses.add("数学");
        originalCourses.add("英语");
        Student originalStudent = new Student("张三", originalAddress, originalCourses);

        Student shallowCopyStudent = (Student) originalStudent.clone();
        shallowCopyStudent.getAddress().setCity("江苏");
        shallowCopyStudent.getCourses().add("语文");
        System.out.println("浅拷贝后：");
        System.out.println("原对象: " + originalStudent);
        System.out.println("浅拷贝对象: " + shallowCopyStudent);

        Student deepCopyStudent = originalStudent.deepCopy();
        deepCopyStudent.getAddress().setCity("浙江");
        deepCopyStudent.getCourses().add("历史");
        System.out.println("\n深拷贝后：");
        System.out.println("原对象: " + originalStudent);
        System.out.println("深拷贝对象: " + deepCopyStudent);
    }
}